package club.xyes.zkh.ecommerce.security.handler;

import club.xyes.zkh.ecommerce.commons.context.ApplicationConstants;
import club.xyes.zkh.ecommerce.commons.vo.GeneralResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 2019/4/15 21:44 Create by 郭文梁（76383）
 * LoginSuccessHandler
 * 登录成功处理器
 *
 * @author 郭文梁
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    private final ObjectMapper objectMapper;

    @Autowired
    public LoginSuccessHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        GeneralResult<Authentication> res = GeneralResult.ok(authentication);
        String respJson = objectMapper.writeValueAsString(res);
        response.setCharacterEncoding(ApplicationConstants.DEFAULT_CHARSET);
        response.setContentType(ApplicationConstants.Http.CONTENT_TYPE_JSON_UTF8);
        response.getWriter().write(respJson);
    }
}
